package com.genghis.ptas.web;

import com.genghis.ptas.classify.entity.Type;
import com.genghis.ptas.classify.entity.TypeValues;
import com.genghis.ptas.classify.service.ClassifyService;
import com.genghis.ptas.classroom.entity.ClassroomInfo;
import com.genghis.ptas.classroom.service.ClassroomService;
import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.course.entity.CourseInfo;
import com.genghis.ptas.course.service.CourseCollectService;
import com.genghis.ptas.course.service.CourseService;
import com.genghis.ptas.homepage.service.HomePageService;
import com.genghis.ptas.note.entity.Note;
import com.genghis.ptas.note.service.NoteService;
import com.genghis.ptas.question.entity.Question;
import com.genghis.ptas.question.service.QuestionService;
import com.genghis.ptas.security.entity.Role;
import com.genghis.ptas.security.entity.User;
import com.genghis.ptas.security.entity.UserBaseInfo;
import com.genghis.ptas.security.service.RoleService;
import com.genghis.ptas.security.service.UserService;
import com.genghis.ptas.task.service.ExaminationService;
import com.genghis.ptas.util.LoginUserUtil;
import com.genghis.ptas.util.Page;
import com.genghis.ptas.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: gao yang
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/public")
public class PublicController {
    @Autowired
    private UserService userService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private ClassifyService classifyService;

    @Autowired
    private CourseCollectService courseCollectService;

    @Autowired
    private ClassroomService classroomService;

    @Autowired
    private NoteService noteService;

    @Autowired
    private ExaminationService examinationService;

    @Autowired
    private HomePageService homePageService;

    @Autowired
    private QuestionService questionService;

    @RequestMapping(value = "index", method = {RequestMethod.GET})
    public String index(HttpServletRequest request) {
        return userService.returnIndexPage(request);
    }

    @RequestMapping(value = "content", method = {RequestMethod.GET})
    public String content(HttpServletRequest request) {
        String loginName = LoginUserUtil.findLoginUserName();
        Integer pageNumber = courseService.findCourseList().size() / DictConstant.PAGE;
        request.setAttribute("pageNumber", pageNumber);
        if (null != loginName) {
            User user = userService.findUserByLoginName(loginName);
            Role role = roleService.findRoleByUserId(user.getId());
            request.setAttribute("isLogin", true);
            request.setAttribute("notLogin", false);
            if (DictConstant.ROLE_SYSTEM.equals(role.getRoleName())) {
                request.setAttribute("isSystem", true);
                return "index";
            }
        } else {
            request.setAttribute("isLogin", false);
            request.setAttribute("notLogin", true);
        }
        return "frontstage/public/contentDo";
    }

    @RequestMapping(value = "register", method = {RequestMethod.GET})
    public String register() {
        return "frontstage/public/register";
    }

    @RequestMapping(value = "menu", method = {RequestMethod.GET})
    public String menu(HttpServletRequest request) {
        List<Type> typeList = classifyService.findAllType();
        String loginName = LoginUserUtil.findLoginUserName();
        request.setAttribute("typeList", typeList);
        request.setAttribute("isLogin", null != loginName);
        if (null != loginName) {
            User user = userService.findUserByLoginName(loginName);
            request.setAttribute("courseCollect", courseCollectService.findCourseCollectByUserId(user.getId()));
        }
        return "includes/menu";
    }

    @RequestMapping(value = "registerDo", method = {RequestMethod.POST})
    public String addUser(User user, UserBaseInfo userBaseInfo) {
        try {
            user.setUserBaseInfo(userBaseInfo);
            user.setRoleId(roleService.findRoleByRoleName(DictConstant.ROLE_USER).getId());
            userService.addUser(user);
            return "redirect:/login";
        } catch (Exception e) {
            return "frontstage/public/register";
        }
    }

    @RequestMapping(value = "listCourseDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String listCourseDo(HttpServletRequest request, @RequestParam("typeId") String typeId) {
        request.setAttribute("typeId", typeId);
        return "frontstage/course/listCourseDo";
    }

    @RequestMapping(value = "courseList", method = {RequestMethod.GET, RequestMethod.POST})
    public String courseList(HttpServletRequest request, @RequestParam("typeId") String typeId) {
        String searchName = request.getParameter("searchName");
        searchName = StringUtil.iso2utf(searchName);
        String loginName = LoginUserUtil.findLoginUserName();
        List<CourseInfo> top = homePageService.findTopCourseByTypeValueId(Integer.parseInt(typeId));
        List<CourseInfo> courseList = courseService.findCourseListByTypeIdAndName(Integer.parseInt(typeId), searchName);
        int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
        int pageCount = request.getParameter("pageCount") == null ? 9 : Integer.parseInt(request.getParameter("pageCount"));
        Map map = Page.getPageMap(page, pageCount, courseList.size());
        TypeValues typeValues = classifyService.findTypeValuesById(Integer.parseInt(typeId));
        request.setAttribute("courseList", courseList);
        request.setAttribute("pageMap", map);
        request.setAttribute("typeValues", typeValues);
        request.setAttribute("isLogin", null != loginName);
        request.setAttribute("top", top);
        request.setAttribute("courseHot", courseList);
        request.setAttribute("courseInfoListSize", courseList.size());
        request.setAttribute("countPage", courseList.size() / 9 + 1);
        request.setAttribute("searchName", searchName);
        request.setAttribute("typeId", typeId);
        return "frontstage/course/courseList";
    }

    @RequestMapping(value = "checkRepeatLoginName", method = {RequestMethod.POST})
    @ResponseBody
    public boolean checkRepeatPermissionToken(@RequestParam("loginName") String loginName, @RequestParam("forgetPassword") Boolean forgetPassword, @RequestParam("oldName") String oldName) {
        if (forgetPassword) {
            return !userService.checkRepeatLoginName(loginName, oldName);
        } else {
            return userService.checkRepeatLoginName(loginName, oldName);
        }
    }

    @RequestMapping(value = "publicityNote", method = {RequestMethod.GET})
    public String publicityNote(HttpServletRequest request, Note note) {
        String search = request.getParameter("search");
        if (null != search)
            note.setNoteContent(StringUtil.iso2utf(search));
        List<Note> notes = noteService.findAllPublicNote(note);
        int page = null == request.getParameter("page") || "".equals(request.getParameter("page")) ? 1 : Integer.parseInt(request.getParameter("page"));
        int pageCount = 10;
        Map map = Page.getPageMap(page, pageCount, notes.size());
        request.setAttribute("pageMap", map);
        request.setAttribute("notes", notes);
        return "frontstage/note/publicityNote";
    }

    @RequestMapping(value = "queryResultList", method = {RequestMethod.GET, RequestMethod.POST})
    public String queryResultList(HttpServletRequest request) throws UnsupportedEncodingException {
        String courseName = new String(request.getParameter("query").getBytes("ISO8859-1"), "UTF-8");
        List<CourseInfo> courseInfoList = courseService.findCourseListByCourseName(courseName);
        List<CourseInfo> courseSystemList = homePageService.findCourseSystemList();
        request.setAttribute("isLogin", null != LoginUserUtil.findLoginUserName());
        request.setAttribute("courseName", courseName);
        request.setAttribute("courseSystemList", courseSystemList);
        request.setAttribute("courseInfoList", courseInfoList);
        return "frontstage/course/queryResultList";
    }

    @RequestMapping(value = "clauseInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public String clauseInfo() {
        return "clause";
    }

    @RequestMapping(value = "questionListDo", method = {RequestMethod.POST, RequestMethod.GET})
    public String questionListDo(HttpServletRequest request) {
        String content = request.getParameter("write");
        List<Question> questionList = questionService.findAllQuestionByContent(content);
        int page = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
        int pageCount = 7;
        Map map = Page.getPageMap(page, pageCount, questionList.size());
        request.setAttribute("isLogin", null != LoginUserUtil.findLoginUserName());
        request.setAttribute("pageMap", map);
        request.setAttribute("questionList", questionList);
        return "frontstage/question/questionListDo";
    }

    @RequestMapping(value = "userEnterListAllClassroomDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String userEnterListAllClassroomDo(HttpServletRequest request) {
        Integer page = 1;
        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        List<ClassroomInfo> classroomInfoList = classroomService.findAllClassroomInfoList();
        request.setAttribute("pageNumber", classroomInfoList.size() / 8);
        request.setAttribute("classroomInfoList", classroomInfoList.subList((page - 1) * 8, Math.min(page * 8, classroomInfoList.size())));
        return "frontstage/classroom/listAllClassroomDo";
    }

    @RequestMapping(value = "enterClassroomInfoDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String enterClassroomInfoDo(HttpServletRequest request, @RequestParam("id") Integer id) {
        ClassroomInfo classroomInfo = classroomService.findClassroomInfoById(id);
        request.setAttribute("classroomInfo", classroomInfo);
        if (LoginUserUtil.findLoginUserName() != null) {
            int userId = userService.findUserByLoginName(LoginUserUtil.findLoginUserName()).getId();
            request.setAttribute("planInfo", classroomService.findClassroomCourseByClassroomInfoIdAndUserId(id, userId));
            request.setAttribute("isLogin", null != LoginUserUtil.findLoginUserName());
            request.setAttribute("expend", classroomService.findExpendClassroom(classroomInfo.getName()));
        } else {
            request.setAttribute("planInfo", classroomService.findClassroomCourseByClassroomInfoId(id));
            request.setAttribute("isLogin", null != LoginUserUtil.findLoginUserName());
            request.setAttribute("expend", classroomService.findExpendClassroom(classroomInfo.getName()));
        }
        return "frontstage/classroom/classroomInfoDo";
    }

    @RequestMapping(value = "userEnterListAllExaminationDo", method = {RequestMethod.GET, RequestMethod.POST})
    public String userEnterListAllExaminationDo(HttpServletRequest request) throws ServletException, IOException {
        List<TypeValues> typeValuesList = classifyService.findAllTypeValue();
        request.setAttribute("examinationInfoList", examinationService.findAllExaminationList());
        request.setAttribute("typeValuesList", typeValuesList);
        return "frontstage/examination/listAllExaminationDo";
    }

    @RequestMapping(value = "forget", method = {RequestMethod.GET, RequestMethod.POST})
    public String forget(HttpServletRequest request, @RequestParam("loginName") String loginName, @RequestParam("question") String question) {
        Boolean isRight = userService.forgetPassword(loginName, question);
        request.setAttribute("notRight", !isRight);
        request.setAttribute("loginName", loginName);
        if (isRight) {
            return "frontstage/public/forgetPasswordDo";
        } else {
            return "frontstage/public/login";
        }
    }

    @RequestMapping(value = "resetPassword", method = {RequestMethod.GET, RequestMethod.POST})
    public String resetPassword(@RequestParam("loginName") String loginName, @RequestParam("password") String password) {
        userService.resetPassword(loginName, password);
        return "frontstage/public/login";
    }

    @RequestMapping(value = "initPhotoUrl", method = {RequestMethod.POST})
    @ResponseBody
    public User checkRepeatPermissionToken(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        UserBaseInfo userBaseInfo = userService.findUserBaseInfoByUserId(user.getId());
        user.setUserBaseInfo(userBaseInfo);
        return user;
    }
}
